package org.sample.programs;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListFilesDemoActivity extends Activity
{
	private final String folderPath = "/sdcard/Songs/";
	
	private List<String> filesNameFromFolder = null;
	private List<ListItem> listitems = null;
	private ListItemAdapter adapter = null;
	private ListView listView = null;
	private File folder = null;
	private File[] filesFromFolder = null;
	
	//private View listHeader = null;
	
	private String newFileName = "";
	private String menuItemName = "";
	private String listItemName = ""; 
	
	private Timer myTimer = null;
	
	private long lastModified = 1l;
	private long currentlyModified = 1l;
	
	
	private List<String> getFilesNameFromFolder(String DirectoryPath) 
	{
		folder = new File(DirectoryPath);
		folder.mkdirs();
		
		filesFromFolder = folder.listFiles();
		
		for (int i = 0; i < filesFromFolder.length; i++)
		{
			if(filesFromFolder[i].length()<=0)
			{
				filesFromFolder[i].delete();
			}
		}
		
		lastModified = folder.lastModified();
		
		if (filesFromFolder.length == 0)
		{
			return null;
		}
		else 
		{
			return Arrays.asList(folder.list());
		}
	}
	
	private void displayItemsInList()
	{
		filesNameFromFolder = getFilesNameFromFolder(folderPath);
		
		listitems = new ArrayList<ListItem>();

		for(int i=0; i<filesFromFolder.length; i++)
		{
			listitems.add(new ListItem(R.drawable.left,filesFromFolder[i].getName(),R.drawable.right));
		}
		
		
		if(filesNameFromFolder==null)
		{
		    listView = (ListView)findViewById(R.id.list);
		    //listHeader = (View)getLayoutInflater().inflate(R.layout.listviewheader, null);
		    //listView.addHeaderView(listHeader);
		    listView.setOnItemClickListener(new OnItemClickListener() 
			{
				public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			    {
					view.showContextMenu();
			    }
			});
		    adapter = new ListItemAdapter(this, R.layout.listviewitem, listitems);
		    unregisterForContextMenu(listView);
		    listView.setAdapter(null); 
		}
		else
		{
			listView = (ListView)findViewById(R.id.list);
			//listHeader = (View)getLayoutInflater().inflate(R.layout.listviewheader, null);
			//listView.addHeaderView(listHeader);
			adapter = new ListItemAdapter(this, R.layout.listviewitem, listitems);
			listView.setAdapter(adapter);
			
			listView.setOnItemClickListener(new OnItemClickListener() 
			{
				public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			    {
					if(view!=null)
					{
						view.showContextMenu();
					}
			    }
			});
			registerForContextMenu(listView);
		}
	}
	
	private void showExitAlert() 
	{
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(ListFilesDemoActivity.this);
		alertDialog.setTitle("Exit Alert Dialog Box");
		alertDialog.setMessage("Are you sure that you want to exit this application");

		alertDialog.setPositiveButton("Yes",new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int id) 
			{
				 finish();
			}
		});
		
		alertDialog.setNeutralButton("No",new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int id) 
			{
				onPause();
			}
		});

		alertDialog.show();
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        displayItemsInList();
        
        myTimer = new Timer();
		myTimer.schedule(new TimerTask() {			
			@Override
			public void run() {
				TimerMethod();
			}
			
		}, 0, 3000);
    }
	
	private void TimerMethod()
	{
		this.runOnUiThread(Timer_Tick);
	}

	private Runnable Timer_Tick = new Runnable()
	{
		public void run() 
		{
			if(folder!=null)
			{
				currentlyModified = folder.lastModified();
			}
			
			if(currentlyModified!=0 && lastModified<currentlyModified)
			{
				displayItemsInList();
			}
		}
	};
	
	 @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event)
	 {
	     if(keyCode == KeyEvent.KEYCODE_BACK)
	     {
	         Log.i("List Files Demo", "Back button pressed!");
	         showExitAlert();
	     }
	     return super.onKeyDown(keyCode, event);
	 }
	 
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
    {
    	if (v.getId()==R.id.list)
    	{
    	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    		menu.setHeaderTitle(filesNameFromFolder.get(info.position));
    		String[] menuItems = getResources().getStringArray(R.array.menu); 
    		for (int i = 0; i<menuItems.length; i++) 
    		{
    			menu.add(Menu.NONE, i, i, menuItems[i]);
			}
    	}
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	    int menuItemIndex = item.getItemId();
		String[] menuItems = getResources().getStringArray(R.array.menu);
		menuItemName = menuItems[menuItemIndex];
	    listItemName = filesNameFromFolder.get(info.position);
	    
	    if(menuItemName.equals("Play"))
	    {
	    	Log.i("List Files Demo","Play operation performed on : "+listItemName);
    	    try 
    	    {
    	    	String audioFilePath = folderPath+listItemName;
    	    	
    	    	Intent intent = new Intent(); 
	            intent.setAction(android.content.Intent.ACTION_VIEW);  
	            File file = new File(audioFilePath);  
	            intent.setDataAndType(Uri.fromFile(file), "audio/*");  	          
	            startActivity(intent);
    	    } 
    	    catch (IllegalArgumentException e)
    	    {
				e.printStackTrace();
			} 
    	    catch (IllegalStateException e) 
    	    {
				e.printStackTrace();
			} 
	    }
	    
	    else if(menuItemName.equals("Rename"))
	    {
	    	Log.i("List Files Demo","Rename Operation performed on : "+listItemName);
	    	
	    	final Dialog dialog = new Dialog(ListFilesDemoActivity.this);
			dialog.setContentView(R.layout.renamedialog);
			dialog.setTitle("Enter the new file name");
			dialog.setCancelable(true);
			
			Button renameButton = (Button) dialog.findViewById(R.id.renameButton);
			renameButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					EditText renameText =(EditText)dialog.findViewById(R.id.renameText);
					newFileName=renameText.getText().toString();
					
					if(newFileName.length()==0)
					{
						newFileName = listItemName;
					}
					
					File from = new File(folder,listItemName);
			    	File to = new File(folder,newFileName+".amr");
			    	boolean status = from.renameTo(to);
			    	if(status)
			    	{
			    		Toast.makeText(ListFilesDemoActivity.this,"Rename Operation Sucessfull",Toast.LENGTH_LONG).show();
			    	}
			    	else
			    	{
			    		Toast.makeText(ListFilesDemoActivity.this,"Rename Operation failed",Toast.LENGTH_LONG).show();
			    	}
			    	
			    	displayItemsInList();
			    	lastModified = folder.lastModified();
					dialog.dismiss();
				}
			});
			
			Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
			cancelButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Toast.makeText(ListFilesDemoActivity.this,"Rename Operation Canceled",Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
			});
			dialog.show();
	    }
	    
	    else if(menuItemName.equals("Delete"))
	    {
	    	Log.i("List Files Demo","Delete Operation performed on : "+listItemName);
	    	
	    	AlertDialog.Builder alertDialog = new AlertDialog.Builder(ListFilesDemoActivity.this);

			alertDialog.setTitle(listItemName);
			alertDialog.setMessage("Are you sure that you want to delete this file");

			alertDialog.setPositiveButton("Yes",new DialogInterface.OnClickListener() 
			{
				public void onClick(DialogInterface dialog, int id) 
				{
					Log.i("Delete AlertBox", "Yes Button clicked");
	
			    	File file = new File(folder,listItemName);
			    	boolean status = file.delete();
			    	if(status)
			    	{
			    		Toast.makeText(ListFilesDemoActivity.this,"Delete Operation Sucessfull",Toast.LENGTH_LONG).show();
			    	}
			    	else
			    	{
			    		Toast.makeText(ListFilesDemoActivity.this,"Delete Operation failed",Toast.LENGTH_LONG).show();
			    	}
			    	
			    	displayItemsInList();
			    	lastModified = folder.lastModified();
				}
			});

			alertDialog.setNeutralButton("No",new DialogInterface.OnClickListener() 
			{
				public void onClick(DialogInterface dialog, int id)
				{
					Log.i("Delete AlertBox", "No Button clicked");
					Toast.makeText(ListFilesDemoActivity.this,"Delete Operation Canceled",Toast.LENGTH_LONG).show();
					onPause();
				}
			});	  
			alertDialog.show();
	    }
    	return true;
    }
}